<!--
 * @author wangpeizhi
 新建/编辑闯关
 -->
<template>
  <div class="rush-manage">
    <div class="rush-manage-title">新建/编辑闯关</div>
    <section v-loading="loading" class="rush-manage-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="闯关名称" prop="dailyName">
          <el-input v-model="form.dailyName" placeholder="请输入闯关名称" />
        </el-form-item>
        <el-form-item label="闯关分类" prop="classifyIds">
          <el-cascader v-if="showClassify" ref="classify" v-model="form.classifyIds" :options="classifyOptions" style="width:100%" clearable :props="classifyProps" />
        </el-form-item>
        <el-form-item label="闯关图片" prop="dailyImg" required>
          <image-upload
            :key="upload.imagecropperKey"
            v-model="form.dailyImg"
            :preview-id="upload.viewId"
            :forever="true"
            :width="330"
            :view="upload.view"
            :height="140"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="upload.isOss"
            @changeOssPath="(path) =>{upload.viewId = path}"
          />
        </el-form-item>
        <el-form-item label="出题数量" prop="questionNumber">
          <el-input v-model.number="form.questionNumber" placeholder="请输入出题数量" @focus="type = 2" />
        </el-form-item>
        <el-form-item label="闯关成功题数" prop="succNumber">
          <el-input v-model.number="form.succNumber" placeholder="请输入闯关成功题数" />
        </el-form-item>
        <el-form-item label="每题分值" prop="questionScore">
          <el-input v-model.number="form.questionScore" placeholder="请输入每题分值" />
        </el-form-item>
        <el-form-item label="闯关成功分值系数" prop="succScoreCoefficient">
          <el-input v-model="form.succScoreCoefficient" placeholder="请输入闯关成功分值系数" />
        </el-form-item>
        <el-form-item label="闯关失败分值系数" prop="failScoreCoefficent">
          <el-input v-model="form.failScoreCoefficent" placeholder="请输入闯关失败分值系数" />
        </el-form-item>
        <el-form-item label="闯关时长（秒)" prop="breakthroughDuration">
          <el-input v-model.number="form.breakthroughDuration" placeholder="请输入闯关时长" />
        </el-form-item>
        <!-- <el-form-item label="成功积分" :prop="points4s == '1' ? 'succPoints': ''">
          <el-row>
            <el-col :span="6">
              <el-input v-model="form.succPoints" :disabled="points4s == -1 || points4s == -9999" placeholder="请输入成功积分" />
            </el-col>
            <el-col :span="2">&nbsp;</el-col>
            <el-col :span="16">
              <el-radio-group v-model="points4s" @change="handleChangePoints4f">
                <el-radio :label="-9999">跟系统配置一致</el-radio>
                <el-radio :label="1">自定义</el-radio>
                <el-radio :label="-1">跟闯关成功分值一致</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="失败积分" :prop="points4f == '1' ? 'failPoints': ''">
          <el-row>
            <el-col :span="6">
              <el-input v-model="form.failPoints" :disabled="points4f == -1 || points4f == -9999" placeholder="请输入失败积分" />
            </el-col>
            <el-col :span="2">&nbsp;</el-col>
            <el-col :span="16">
              <el-radio-group v-model="points4f" @change="handleChangePoints4f">
                <el-radio :label="-9999">跟系统配置一致</el-radio>
                <el-radio :label="1">自定义</el-radio>
                <el-radio :label="-1">跟闯关失败分值一致</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-form-item> -->
        <!-- <el-form-item label="每日积分上限">
          <el-row>
            <el-col :span="6">
              <el-input v-model.number="form.everydayPointsLimit" :disabled="unlimited" placeholder="每日积分上限" />
            </el-col>
            <el-checkbox v-model="unlimited" style="margin-left: 20px;">无上限</el-checkbox>
          </el-row>
        </el-form-item> -->
        <el-form-item label="是否为推荐闯关" prop="recommendFlag">
          <el-radio-group v-model="form.recommendFlag">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>

    <section class="rush-manage-footer">
      <el-button style="padding: 10px 30px;" @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
  </div>
</template>
<script>
import { specialText, int, doublescore, intwith } from '@/utils/validate'
import { mapGetters } from 'vuex'
import ImageUpload from '@/components/ImageUpload'
import {
  getDictByCode,
  getClassifyTree,
  insert,
  update,
  get
} from './../api/rush'
export default {
  name: 'RushManage',
  components: { ImageUpload },
  data() {
    return {
      loading: false,
      unlimited: false,
      form: {
        id: '',
        deptId: '-1',
        dailyName: '',
        dailyImg: '',
        classifyId: '',
        classifyIds: [],
        questionNumber: '',
        succNumber: '',
        questionScore: '1',
        succScoreCoefficient: '1',
        failScoreCoefficent: '1',
        breakthroughDuration: '',
        succPoints: '1',
        failPoints: '1',
        sort: '',
        recommendFlag: 0,
        status: 'BDZT02',
        everydayPointsLimit: -1
      },
      rules: {
        dailyName: [
          { required: true, message: '请输入闯关名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        recommendFlag: [
          { required: true, message: '请选择是否为推荐闯关', trigger: 'blur' }
        ],
        classifyIds: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        questionNumber: [
          { required: true, message: '请输入出题数量', trigger: 'blur' },
          { trigger: 'blur', validator: int }
        ],
        succNumber: [
          { required: true, message: '请输入闯关成功题数', trigger: 'blur' },
          { trigger: 'blur', validator: intwith }
        ],
        questionScore: [
          { required: true, message: '请输入每题分值', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        succScoreCoefficient: [
          { required: true, message: '请输闯关成功分值系数', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        failScoreCoefficent: [
          { required: true, message: '请输入闯关失败分值系数', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        breakthroughDuration: [
          { required: true, message: '请输入闯关时长', trigger: 'blur' },
          { trigger: 'blur', validator: int }
        ],
        succPoints: [
          { required: true, message: '请输入成功积分', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        failPoints: [
          { required: true, message: '请输入失败积分', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      },
      points4s: -9999,
      points4f: -9999,
      upload: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
      },
      classifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      classifyOptions: [],
      showClassify: false,
      state: 'create',
      t: '0',
      dict: {
        BDZT: [] // 状态
      },
      type: 1
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  watch: {
    unlimited(val) {
      if (val) {
        this.form.everydayPointsLimit = -1
      } else {
        this.form.everydayPointsLimit = ''
      }
    },
    'form.classifyIds': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    },
    'form.questionNumber': {
      handler(newName, oldName) {
        if (newName && this.type === 2) {
          this.form.succNumber = newName
          this.form.breakthroughDuration = Number(newName) * 15
        }
      },
      immediate: true,
      deep: true
    },
    'form.succNumber': {
      handler(newName, oldName) {
        if (Number(newName) > this.form.questionNumber) {
          this.$message({
            showClose: true,
            message: '闯关成功题数不能大于出题数！',
            type: 'warning'
          })
          this.form.succNumber = this.form.questionNumber
        }
      },
      immediate: true,
      deep: true
    },
    'points4s': {
      handler(newName, oldName) {
        this.form.succPoints = newName
      },
      immediate: true,
      deep: true
    },
    'points4f': {
      handler(newName, oldName) {
        this.form.failPoints = newName
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getClassify()
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showClassify = true
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 获取分类
     */
    getClassify() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL02' }).then(({ data }) => {
          this.classifyOptions = data.data || []
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'dailyImg') {
              this.form[key] = data.dailyImg
              this.upload.viewId = data.dailyImgUrl
            } else if (key === 'classifyIds') {
              this.form[key] = Object.assign([], (data.classifyIds && data.classifyIds.split(',')))
            } else if (key === 'succPoints') {
              this.form[key] = data[key]
              this.points4s = data[key]
            } else if (key === 'failPoints') {
              this.form[key] = data[key]
              this.points4f = data[key]
            } else if (key === 'recommendFlag') {
              this.form[key] = data[key] || 0
            } else if (key === 'everydayPointsLimit' && data[key] && data[key] === -1) {
              this.unlimited = true
            } else {
              this.form[key] = data[key]
            }
          }
          this.$nextTick(() => {
            this.showClassify = true
          })
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },

    /**
     * 取消闯关维护
     */
    onCancel() {
      this.$router.push({ path: this.$filterPath('index'), query: { t: this.t }})
    },

    /**
     * 发布闯关
     */
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const {
              id,
              deptId,
              dailyName,
              dailyImg,
              questionNumber,
              succNumber,
              questionScore,
              succScoreCoefficient,
              failScoreCoefficent,
              breakthroughDuration,
              succPoints,
              failPoints,
              sort,
              recommendFlag,
              status,
              everydayPointsLimit
            } = this.form
            return new Promise((resolve, reject) => {
              insert({
                id,
                deptId,
                dailyName,
                dailyImg,
                questionNumber,
                succNumber,
                questionScore,
                succScoreCoefficient,
                failScoreCoefficent,
                breakthroughDuration,
                succPoints,
                failPoints,
                sort,
                recommendFlag,
                status,
                everydayPointsLimit,
                classifyId: this.form.classifyIds.length > 0 ? this.form.classifyIds[this.form.classifyIds.length - 1] : ''

              }).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.push({ path: this.$filterPath('index') })
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const {
              id,
              deptId,
              dailyName,
              dailyImg,
              questionNumber,
              succNumber,
              questionScore,
              succScoreCoefficient,
              failScoreCoefficent,
              breakthroughDuration,
              succPoints,
              failPoints,
              sort,
              recommendFlag,
              status,
              everydayPointsLimit
            } = this.form
            return new Promise((resolve, reject) => {
              update({
                id,
                deptId,
                dailyName,
                dailyImg,
                questionNumber,
                succNumber,
                questionScore,
                succScoreCoefficient,
                failScoreCoefficent,
                breakthroughDuration,
                succPoints,
                failPoints,
                sort,
                recommendFlag,
                status,
                everydayPointsLimit,
                classifyId: this.form.classifyIds.length > 0 ? this.form.classifyIds[this.form.classifyIds.length - 1] : ''
              }).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.push({ path: this.$filterPath('index') })
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },
    handleChangePoints4f(val) {
      if (val !== -9999) {
        this.$message(
          {
            type: 'warning',
            message: '与每日任务积分配置不一致，请谨慎设置'
          }
        )
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.rush-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .rush-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .rush-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
    .form {
      width: 1000px !important;
      margin: 0 auto;
      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }
    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;
      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }
    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
    }
  }

  .rush-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
<style lang="scss">
.rush-manage {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;
    .classify-tree-con-scrollbar {
      overflow: hidden;
      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }
    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;
      .tree-node-txt {
        flex: 1;
      }
    }
  }
}
</style>

